<template>
  <div class="public-welfare-activities">
    <!-- 表格组件，传入表头和数据 -->
    <FormComponent :label-arr="labArr" :table-data="activitiesArr">
      <el-table-column label="活动图片" width="200">
        <template v-slot="scope">
          <!-- 图片展示 -->
          <img :src="getImageUrl(scope.row.image)" alt="活动图片" style="max-width: 50%; height: auto;"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="270">
        <template v-slot="scope">
          <!-- 删除按钮 -->
          <button
              style="height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;float: none"
              @click="deleteActivity(scope.$index)">删除
          </button>

          <!-- 编辑按钮 -->
          <button
              style="height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;margin-left:20px;float: none"
              @click="editActivity(scope.$index)">编辑
          </button>
        </template>
      </el-table-column>
    </FormComponent>

    <!-- 添加活动按钮 -->
    <el-button @click="showAddDialog">添加公益活动</el-button>

    <!-- 分页控制 -->
    <el-pagination
        :current-page="currentPage"
        :page-size="5"
        :total="total"
        @current-change="handlePageChange">
    </el-pagination>

    <!-- 编辑或添加公益活动的对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑公益活动' : '添加公益活动'"
        :visible="dialogVisible"
        @close="dialogVisible = false"
        width="50%">
      <el-form :model="editingActivity">
        <el-form-item label="活动标题">
          <el-input v-model="editingActivity.title" />
        </el-form-item>
        <el-form-item label="活动内容">
          <el-input v-model="editingActivity.content" />
        </el-form-item>
        <el-form-item label="发布说明">
          <el-input v-model="editingActivity.publishTime" disabled />
        </el-form-item>
        <el-form-item label="活动图片">
          <!-- 使用 input[type="file"] 来上传文件 -->
          <input type="file" @change="handleFileChange" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditOrAdd">{{ isEdit ? '提交' : '添加' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import FormComponent from "@/components/form/modle/FormComponent.vue";

// 定义表格头部字段
let labArr = ref([
  { title: "活动标题" },
  { content: "活动内容" },
  { publishTime: "发布时间" },
]);

// 存储公益活动数据
let activitiesArr = ref([]);
let total = ref(0);

// 存储当前编辑的公益活动
let editingActivity = ref({
  title: "",
  content: "",
  publishTime: "",
  image: "",
});

let dialogVisible = ref(false);
let isEdit = ref(false); // 判断是否为编辑模式

const consultantId = JSON.parse(localStorage.getItem("key")).data?.consultantId;
if (!consultantId) {
  console.error("未找到consultantId");
}

// 获取公益活动数据
const getActivities = (pageNum = 1, pageSize = 5) => {
  if (!consultantId) return;

  axios
      .get(`http://127.0.0.1:9090/publicWelfareActivities/${consultantId}`, {
        params: { pageNum, pageSize },
      })
      .then((response) => {
        const data = response.data;
        activitiesArr.value = data.list.map((item) => ({
          title: item.title,
          content: item.content,
          publishTime: item.publishTime,
          image: item.image,
          activityId: item.activityId,
        }));
        total.value = data.total;
      })
      .catch((error) => {
        console.error("获取公益活动失败", error);
      });
};

onMounted(() => {
  getActivities(); // 默认获取第一页数据
});

const currentPage = ref(1);

// 处理分页变化
const handlePageChange = (pageNum) => {
  currentPage.value = pageNum;
  getActivities(pageNum, 5);
};

// 删除公益活动
const deleteActivity = (index) => {
  const activityId = activitiesArr.value[index].activityId;
  axios
      .delete(`http://127.0.0.1:9090/publicWelfareActivities/${activityId}`)
      .then(() => {
        getActivities(currentPage.value, 5); // 删除后重新获取数据
      })
      .catch((error) => {
        console.error("删除失败", error);
      });
};

// 编辑公益活动
const editActivity = (index) => {
  const activity = activitiesArr.value[index];
  editingActivity.value = { ...activity }; // 将活动内容复制到编辑表单
  dialogVisible.value = true; // 弹出对话框
  isEdit.value = true; // 设置为编辑模式
};

// 获取当前本地时间的函数
const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 提交修改或添加
const submitEditOrAdd = () => {
  const currentTime = getCurrentTime();

  // 如果是编辑，使用上传后的图片名或原图片名
  if (isEdit.value) {
    editingActivity.value.publishTime = currentTime;
    editingActivity.value.consultantId = consultantId;
    editingActivity.value.image = uploadedImage.value || editingActivity.value.image;

    // 调用修改接口
    axios
        .put("http://127.0.0.1:9090/publicWelfareActivities", editingActivity.value, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then(() => {
          getActivities(currentPage.value, 5);
          dialogVisible.value = false;
        })
        .catch((error) => {
          console.error("修改失败", error);
        });
  } else {
    // 如果是添加，传递上传的图片文件名
    editingActivity.value.consultantId = consultantId;
    editingActivity.value.publishTime = currentTime;
    editingActivity.value.image = uploadedImage.value; // 使用新上传的图片文件名

    // 调用添加接口
    axios
        .post("http://127.0.0.1:9090/publicWelfareActivities", editingActivity.value, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then(() => {
          getActivities(currentPage.value, 5);
          dialogVisible.value = false;
        })
        .catch((error) => {
          console.error("添加失败", error);
        });
  }
};

// 显示添加对话框
const showAddDialog = () => {
  editingActivity.value = { title: "", content: "", publishTime: getCurrentTime(), image: "" };
  isEdit.value = false;
  dialogVisible.value = true;
};

// 获取图片的二进制路径
const getImageUrl = (fileName) => {
  return `http://127.0.0.1:9090/file/download/byte/${fileName}`; // 后端返回的图片路径
};

// 图片上传部分
const uploadedImage = ref(""); // 用于存储上传后的图片文件名

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData();
    formData.append("file", file);  // 添加图片文件

    // 发送图片文件到后端并获取 UUID 编码后的图片名
    axios
        .post("http://127.0.0.1:9090/file/uploadsn", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          // 假设返回的图片文件名是 UUID 格式
          uploadedImage.value = response.data.additionalData.fileNames[0];
          console.log("图片上传成功", response);
        })
        .catch((error) => {
          console.error("图片上传失败", error);
        });
  }
};
</script>
